import { Request, Response } from 'express';
import { CaseService } from '../services/caseService';
import type { CreateCaseRequest, UpdateCaseRequest } from '../types/case';
import * as ExcelJS from 'exceljs';

const caseService = new CaseService();

export class CaseController {
  // 获取案例列表 (用户端)
  async getCases(req: Request, res: Response) {
    try {
      const { page, limit, categoryId, keyword, sort } = req.query;
      
      const params = {
        page: page ? parseInt(page as string) : 1,
        limit: limit ? parseInt(limit as string) : 10,
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        status: true, // 用户端只显示已发布的案例
        keyword: keyword as string,
        sort: sort as string
      };

      const result = await caseService.getCases(params);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      console.error('获取案例列表失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例列表失败'
      });
    }
  }

  // 获取单个案例详情 (用户端)
  async getCaseBySlug(req: Request, res: Response) {
    try {
      const { slug } = req.params;
      const caseData = await caseService.getCaseBySlug(slug);
      
      if (!caseData) {
        return res.status(404).json({
          success: false,
          error: '案例不存在'
        });
      }

      res.json({
        success: true,
        data: caseData
      });
    } catch (error) {
      console.error('获取案例详情失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例详情失败'
      });
    }
  }

  // 获取推荐案例 (用户端)
  async getRecommendCases(req: Request, res: Response) {
    try {
      const { limit } = req.query;
      const cases = await caseService.getRecommendCases(limit ? parseInt(limit as string) : 5);
      
      res.json({
        success: true,
        data: cases
      });
    } catch (error) {
      console.error('获取推荐案例失败:', error);
      res.status(500).json({
        success: false,
        error: '获取推荐案例失败'
      });
    }
  }

  // 获取置顶案例 (用户端)
  async getTopCases(req: Request, res: Response) {
    try {
      const { limit } = req.query;
      const cases = await caseService.getTopCases(limit ? parseInt(limit as string) : 3);
      
      res.json({
        success: true,
        data: cases
      });
    } catch (error) {
      console.error('获取置顶案例失败:', error);
      res.status(500).json({
        success: false,
        error: '获取置顶案例失败'
      });
    }
  }

  // 获取案例分类 (用户端)
  async getCaseCategories(req: Request, res: Response) {
    try {
      const categories = await caseService.getAllCaseCategories();
      
      res.json({
        success: true,
        data: categories
      });
    } catch (error) {
      console.error('获取案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例分类失败'
      });
    }
  }

  // === 管理端接口 ===

  // 获取案例列表 (管理端)
  async getAdminCases(req: Request, res: Response) {
    try {
      const { page, limit, categoryId, status, keyword, userId, sort } = req.query;
      
      const params = {
        page: page ? parseInt(page as string) : 1,
        limit: limit ? parseInt(limit as string) : 10,
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        status: status !== undefined ? String(status) === 'true' : undefined,
        keyword: keyword as string,
        userId: userId ? parseInt(userId as string) : undefined,
        sort: sort as string
      };

      const result = await caseService.getCases(params);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      console.error('获取案例列表失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例列表失败'
      });
    }
  }

  // 获取单个案例详情 (管理端)
  async getCaseById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const caseData = await caseService.getCaseById(parseInt(id));
      
      if (!caseData) {
        return res.status(404).json({
          success: false,
          error: '案例不存在'
        });
      }

      res.json({
        success: true,
        data: caseData
      });
    } catch (error) {
      console.error('获取案例详情失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例详情失败'
      });
    }
  }

  // 创建案例 (管理端)
  async createCase(req: Request, res: Response) {
    try {
      const caseData: CreateCaseRequest = req.body;
      const userId = req.user?.id;

      const newCase = await caseService.createCase(caseData, userId);
      
      res.status(201).json({
        success: true,
        data: newCase
      });
    } catch (error) {
      console.error('创建案例失败:', error);
      res.status(500).json({
        success: false,
        error: '创建案例失败'
      });
    }
  }

  // 更新案例 (管理端)
  async updateCase(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const updateData: UpdateCaseRequest = req.body;
      updateData.id = parseInt(id);

      const updatedCase = await caseService.updateCase(parseInt(id), updateData);
      
      res.json({
        success: true,
        data: updatedCase
      });
    } catch (error) {
      console.error('更新案例失败:', error);
      res.status(500).json({
        success: false,
        error: '更新案例失败'
      });
    }
  }

  // 删除案例 (管理端)
  async deleteCase(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const deleteBy = (req as any).user?.id; // 获取当前操作用户ID
      await caseService.deleteCase(parseInt(id), deleteBy);
      
      res.json({
        success: true,
        message: '案例删除成功'
      });
    } catch (error) {
      console.error('删除案例失败:', error);
      res.status(500).json({
        success: false,
        error: '删除案例失败'
      });
    }
  }

  // 获取案例统计 (管理端)
  async getCaseStats(req: Request, res: Response) {
    try {
      const stats = await caseService.getCaseStats();
      
      res.json({
        success: true,
        data: stats
      });
    } catch (error) {
      console.error('获取案例统计失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例统计失败'
      });
    }
  }

  // === 案例分类管理 ===

  // 获取案例分类列表 (管理端)
  async getAdminCaseCategories(req: Request, res: Response) {
    try {
      const categories = await caseService.getAllCaseCategories();
      
      res.json({
        success: true,
        data: categories
      });
    } catch (error) {
      console.error('获取案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例分类失败'
      });
    }
  }

  // 获取单个案例分类 (管理端)
  async getCaseCategoryById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const category = await caseService.getCaseCategoryById(parseInt(id));
      
      if (!category) {
        return res.status(404).json({
          success: false,
          error: '分类不存在'
        });
      }

      res.json({
        success: true,
        data: category
      });
    } catch (error) {
      console.error('获取案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '获取案例分类失败'
      });
    }
  }

  // 创建案例分类 (管理端)
  async createCaseCategory(req: Request, res: Response) {
    try {
      const categoryData = req.body;
      const newCategory = await caseService.createCaseCategory(categoryData);
      
      res.status(201).json({
        success: true,
        data: newCategory
      });
    } catch (error) {
      console.error('创建案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '创建案例分类失败'
      });
    }
  }

  // 更新案例分类 (管理端)
  async updateCaseCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const updateData = req.body;
      const updatedCategory = await caseService.updateCaseCategory(parseInt(id), updateData);
      
      res.json({
        success: true,
        data: updatedCategory
      });
    } catch (error) {
      console.error('更新案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '更新案例分类失败'
      });
    }
  }

  // 删除案例分类 (管理端)
  async deleteCaseCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      await caseService.deleteCaseCategory(parseInt(id));
      
      res.json({
        success: true,
        message: '案例分类删除成功'
      });
    } catch (error) {
      console.error('删除案例分类失败:', error);
      res.status(500).json({
        success: false,
        error: '删除案例分类失败'
      });
    }
  }

  // 导出案例列表
  async exportCases(req: Request, res: Response) {
    try {
      const {
        categoryId,
        status,
        keyword,
        userId,
        sort,
      } = req.query;

      // 获取所有符合条件的数据（不分页）
      const result = await caseService.getCases({
        page: 1,
        limit: 10000, // 设置一个很大的数字来获取所有数据
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        status: status !== undefined ? String(status) === 'true' : undefined,
        keyword: keyword as string,
        userId: userId ? parseInt(userId as string) : undefined,
        sort: sort as string
      });

      const cases = result.cases;

      // 创建Excel工作簿
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('攻略列表');

      // 设置列标题
      worksheet.columns = [
        { header: '标题', key: 'title', width: 30 },
        { header: '作者', key: 'author', width: 15 },
        { header: '创作者', key: 'creator', width: 15 },
        { header: '发布者', key: 'publisher', width: 15 },
        { header: '阅读数量', key: 'views', width: 12 },
        { header: '发布时间', key: 'publishedAt', width: 20 },
        { header: '创建时间', key: 'createdAt', width: 20 },
        { header: '状态', key: 'status', width: 10 },
        { header: '分类', key: 'category', width: 15 },
        { header: '置顶', key: 'isTop', width: 8 },
        { header: '推荐', key: 'isRecommend', width: 8 },
      ];

      // 添加数据行
      cases.forEach((caseItem: any) => {
        worksheet.addRow({
          title: caseItem.title,
          author: caseItem.author,
          creator: caseItem.user?.username || '未知',
          publisher: caseItem.user?.username || '未知',
          views: caseItem.views,
          publishedAt: caseItem.publishedAt ? new Date(caseItem.publishedAt).toLocaleString('zh-CN') : '未发布',
          createdAt: new Date(caseItem.createdAt).toLocaleString('zh-CN'),
          status: caseItem.status ? '已发布' : '草稿',
          category: caseItem.category?.name || '未分类',
          isTop: caseItem.isTop ? '是' : '否',
          isRecommend: caseItem.isRecommend ? '是' : '否',
        });
      });

      // 设置表头样式
      worksheet.getRow(1).font = { bold: true };
      worksheet.getRow(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE6E6FA' },
      };

      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      const fileName = `攻略列表_${dateStr}.xlsx`;

      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);

      // 写入响应流
      await workbook.xlsx.write(res);
      res.end();
    } catch (error) {
      console.error('导出攻略失败:', error);
      res.status(500).json({
        success: false,
        message: '导出攻略失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }
} 